package com.ocom.payconfig.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ocom.common.entity.card.EntityXfRecordProcess;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.enums.MasterSlaveEnum;
import com.ocom.common.request.payconfig.ConsumeDetailErrorRequest;
import com.ocom.common.request.payconfig.GzhRefundQueryRequest;
import com.ocom.common.request.payconfig.PerDiscountLimitRequest;
import com.ocom.common.request.payhandle.QrCodeMachDailySummaryRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.payconfig.PerDiscountLimitVo;
import com.ocom.mysql.aspect.DataSourceAspect;
import com.ocom.payconfig.dao.IDaoXfRecordProcess;
import com.ocom.payconfig.service.XfRecordProcessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class XfRecordProcessServiceImpl extends ServiceImpl<IDaoXfRecordProcess, EntityXfRecordProcess> implements XfRecordProcessService {

    @Autowired
    private IDaoXfRecordProcess iDaoXfRecordProcess;

    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "companyID")
    @Override
    public int insertEntityXfRecord(Long companyID, EntityXfRecordProcess entityXfRecord) {
        return iDaoXfRecordProcess.insert(entityXfRecord);
    }

    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "companyID")
    @Override
    public int updateEntityXfRecord(Long companyID, EntityXfRecordProcess updateXfRecordProcess) {
        return iDaoXfRecordProcess.updateById(updateXfRecordProcess);
    }

    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "companyID")
    @Override
    public EntityXfRecordProcess selectTradeNo(Long companyID, String tradeNo, String machNo) {
        QueryWrapper<EntityXfRecordProcess> queryWrapper= Wrappers.query();
        queryWrapper.eq("order_no",tradeNo);
        if(!CommonUtil.isNull(machNo)){
            queryWrapper.eq("device_no",machNo);
        }
        queryWrapper.orderByDesc("id");
        queryWrapper.last("limit 1");
        return iDaoXfRecordProcess.selectOne(queryWrapper);
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "companyID")
    public List<EntityXfRecordProcess> selectPlatOrderNo(Long companyID, String platOrderNo) {
        QueryWrapper<EntityXfRecordProcess> queryWrapper= Wrappers.query();
        queryWrapper.eq("plat_order_no",platOrderNo);
        queryWrapper.eq("com_id",companyID);
        return super.list(queryWrapper);
    }

    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "companyID")
    @Override
    public PageInfo<EntityXfRecordProcess> selectGzhRechargePageInfo(Long companyID, GzhRefundQueryRequest request) {
        QueryWrapper<EntityXfRecordProcess> queryWrapper= Wrappers.query();
        queryWrapper.eq("com_id",companyID);
        if(request.getPId()!=null && request.getPId()>0l)queryWrapper.eq("p_id",request.getPId());
        queryWrapper.eq("cons_state",request.getConsState());
        if(request.getPayState()!=null && request.getPayState()>0) queryWrapper.eq("pay_state",request.getPayState());
        queryWrapper.gt("op_type_diff",200);
        if(request.getStartTime()!=null) queryWrapper.gt("cons_time",request.getStartTime());
        queryWrapper.orderByDesc("cons_time");
        PageHelper.startPage(request.getPage(),request.getSize());
        List<EntityXfRecordProcess> pointInfoPageInfo=this.list(queryWrapper);
        PageInfo<EntityXfRecordProcess> pageInfo=new PageInfo<>(pointInfoPageInfo);
        return pageInfo;
    }

    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "companyID")
    @Override
    public List<EntityXfRecordProcess> selectMachDailySummary(Long companyID, QrCodeMachDailySummaryRequest request) {
        QueryWrapper<EntityXfRecordProcess> queryWrapper= Wrappers.query();
        queryWrapper.select("sum(real_money) as amount","count(id) as times","op_type_diff");
        queryWrapper.eq("com_id",companyID);
        queryWrapper.eq("device_no",request.getMachNo());
        queryWrapper.in("cons_state",1,2);
        queryWrapper.apply("date_format(create_time, '%Y-%m-%d')={0}",request.getQueryDate());
        queryWrapper.groupBy("op_type_diff");
        return iDaoXfRecordProcess.selectList(queryWrapper);
    }

    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "companyID")
    @Override
    public Result selectConsumeDetailError(Long companyID, ConsumeDetailErrorRequest request) {
        LambdaQueryWrapper<EntityXfRecordProcess> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EntityXfRecordProcess::getComId, request.getComId())
           //     .gt(EntityXfRecordProcess::getOpTypeDiff, 200)
                .in(EntityXfRecordProcess::getConsState, 1,3,5,10)
                .ge(ObjectUtil.isNotEmpty(request.getStartTime()), EntityXfRecordProcess::getConsTime, request.getStartTime())
                .le(ObjectUtil.isNotEmpty(request.getEndTime()), EntityXfRecordProcess::getConsTime, request.getEndTime())
                .in(ObjectUtil.isNotEmpty(request.getMerchId()), EntityXfRecordProcess::getMerchId, request.getMerchId())
                .in(ObjectUtil.isNotEmpty(request.getPointId()), EntityXfRecordProcess::getPointId, request.getPointId())
                .in(ObjectUtil.isNotEmpty(request.getPayState()), EntityXfRecordProcess::getPayState, request.getPayState())
                .in(ObjectUtil.isNotEmpty(request.getAccTypeId()),EntityXfRecordProcess::getAccTypeId,request.getAccTypeId())
                .in(ObjectUtil.isNotEmpty(request.getDeptId()), EntityXfRecordProcess::getDeptId, request.getDeptId())
                .in(ObjectUtil.isNotEmpty(request.getMealNo()), EntityXfRecordProcess::getMealNo, request.getMealNo())
                .eq(!CommonUtil.isNull(request.getPName()), EntityXfRecordProcess::getPName, request.getPName())
                .eq(ObjectUtil.isNotEmpty(request.getAccountNo()), EntityXfRecordProcess::getAccountNo, request.getAccountNo())
                .eq(ObjectUtil.isNotEmpty(request.getChannelOrderNo()), EntityXfRecordProcess::getChannelOrderNo, request.getChannelOrderNo())
                .eq(ObjectUtil.isNotEmpty(request.getPCode()), EntityXfRecordProcess::getPCode, request.getPCode())
                .eq(ObjectUtil.isNotEmpty(request.getCardNo()), EntityXfRecordProcess::getCardNo, request.getCardNo())
                .eq(ObjectUtil.isNotEmpty(request.getOrderNo()), EntityXfRecordProcess::getOrderNo, request.getOrderNo())
                .orderByDesc(EntityXfRecordProcess::getConsTime);

        if(ObjectUtil.isNotEmpty(request.getDeviceNo())&&!request.getDeviceNo().equals("-1")){
            queryWrapper.eq(EntityXfRecordProcess::getDeviceNo, request.getDeviceNo());
        }
      
        if(ObjectUtil.isEmpty(request.getPage()) || request.getPage()<=0){
            request.setPage(1);
        }
   
        if(ObjectUtil.isEmpty(request.getSize())  || request.getSize()<=0){
            request.setPage(50);
        }
        PageHelper.startPage(request.getPage(), request.getSize());

        List<EntityXfRecordProcess> list = iDaoXfRecordProcess.selectList(queryWrapper);

        PageInfo<EntityXfRecordProcess> pageInfo = new PageInfo<>(list);
        HashMap<String, Object> map = new HashMap<>();
        
//        pageInfo.getList().forEach(process->{
//
//                }
//        );

        map.put("list",pageInfo.getList());
        map.put("total",pageInfo.getTotal());
        return ResultUtil.success(map);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.SLAVE)
    public PerDiscountLimitVo selectUserDiscount(Long companyId, PerDiscountLimitRequest request) {

        PerDiscountLimitVo perDiscountLimitVo =new PerDiscountLimitVo();
        /**
         * 1.查询今天已使用优惠金额
         * select  sum( discount) dayDiscount  from  xf_record_procces
         * where  com_id=@comId  and  p_id=@pId  and  and  cons_type=@consType
         * and  if_refund=0  and  pay_state=1  and  meal_date =’当前日期’ ;
         *
         * 2.查询本月已使用优惠金额
         * select  sum( discount) monthDiscount  from  xf_record_procces
         * where  com_id=@comId  and  p_id=@pId  and  and  cons_type=@consType
         * and  if_refund=0  and  pay_state=1  and   DATE_FORMAT(meal_date, '%Y-%m') meal_date =’当前月份’ ;
         */

        QueryWrapper<EntityXfRecordProcess> queryWrapper= Wrappers.query();
        queryWrapper.select("sum(discount) as amount");
        queryWrapper.eq("com_id",companyId);
        queryWrapper.eq("p_id",request.getPId());
        queryWrapper.eq("cons_type",request.getConsType());
        queryWrapper.in("cons_state",1,3,5);
        queryWrapper.eq("if_refund",0);
        queryWrapper.eq("pay_state",1);
        queryWrapper.eq("meal_date",DateUtils.getDate());
        EntityXfRecordProcess entityXfRecordProcess = this.getOne(queryWrapper);

        QueryWrapper<EntityXfRecordProcess> queryWrapper1= Wrappers.query();
        queryWrapper1.select("sum(discount) as amount");
        queryWrapper1.eq("com_id",companyId);
        queryWrapper1.eq("p_id",request.getPId());
        queryWrapper1.eq("cons_type",request.getConsType());
        queryWrapper1.in("cons_state",1,3,5);
        queryWrapper1.eq("if_refund",0);
        queryWrapper1.eq("pay_state",1);
        queryWrapper1.apply(" DATE_FORMAT(meal_date, '%Y-%m') = {0} " , DateUtils.getStrDate(new Date(),"yyyy-MM"));
        EntityXfRecordProcess entityXfRecordProcess1 = this.getOne(queryWrapper1);

        if(entityXfRecordProcess!=null){
            perDiscountLimitVo.setDayDiscount(Math.abs(entityXfRecordProcess.getAmount()));
        }
        if(entityXfRecordProcess1!=null){
            perDiscountLimitVo.setMonthDiscount(Math.abs(entityXfRecordProcess1.getAmount()));
        }

        return perDiscountLimitVo;
    }







    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId")
    public List<EntityXfRecordProcess> selectPayment(Long comId, Integer consState) {
        QueryWrapper<EntityXfRecordProcess> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("com_id", "order_no");
        queryWrapper.eq("pay_state", 0);
        queryWrapper.eq("cons_state", consState);
        queryWrapper.gt("op_type_diff", 200);
        Date end = new Date( new Date().getTime() - 5*60*1000);//5分钟前的时间
        Date start =new Date( new Date().getTime() - 60*60*1000);//60分钟前的时间
        queryWrapper.between("cons_time", start,end);
//        Date beforeDate = new Date( new Date().getTime() - 5*60*1000);//5分钟前的时间
//        queryWrapper.between("cons_time", DateUtil.addDays(new Date(),-3),beforeDate);
        queryWrapper.orderByAsc("id");
        queryWrapper.last("limit 500");
        return this.list(queryWrapper);
    }
}
